#include <iostream>
#include <cstring>
using namespace std;

class MemoryPool {
private:
	int capacity;
	int* data;
public:
	MemoryPool(int c) {
		if (c <= 0)
		{
			capacity = 0;
			data = NULL;
		}
		else {
			capacity = c;
			data = new int[c];
		}
	}

	MemoryPool(const MemoryPool& a) {
		if (a.data) {
			capacity = a.capacity;
			data = new int[capacity];
			memcpy(data, a.data, sizeof(int) * capacity);
		}
		else {
			capacity = 0;
			data = NULL;
		}
	}

	MemoryPool& operator=(const MemoryPool& a) {
		if (a.data == data)
			return *this;
		if (a.data) {
			if (a.capacity > capacity) {
				delete[]data;
				data = new int[a.capacity];
				capacity = a.capacity;
			}
			else if (capacity > a.capacity) {
				memset(data + a.capacity, 0, sizeof(int) * (capacity - a.capacity));
			}
			memcpy(data, a.data, sizeof(int) * a.capacity);
		}
		else if (data) {
			memset(data, 0, sizeof(int) * capacity);
		}
	}

	int& operator[](int i) { return data[i]; }
	const int& operator[](int i)const { return data[i]; }
};

class CArray {
private:
	int size;
	int capacity;
	int* ptr;
public:
	CArray(int s = 0);
	CArray(const CArray& a);
	~CArray();

	void push_back(int);
	CArray& operator=(const CArray& a);
	int& operator[](int i) { return ptr[i]; }
	int length() { return size; }

private:
	void realloc(int s);
};

void CArray::realloc(int s) {
	if (ptr) {
		if (s > capacity) {
			capacity = s + 10;
			int* tmpPtr = new int[capacity];
			memcpy(tmpPtr, ptr, sizeof(int) * size);
			delete[]ptr;
			ptr = tmpPtr;
		}
	}
	else {
		capacity = s + 10;
		ptr= new int[capacity];
	}
}

CArray::CArray(int s):size(s) {
	ptr = NULL;
	if (s <= 0) {
		capacity = size = 0;
	}
	else {
		realloc(s);
		size = s;
	}
}

CArray::CArray(const CArray& a)
{
	if (!a.ptr) {
		ptr = NULL;
		size = 0;
	}
	else
	{
		size = a.size;
		ptr = new int[size];
		memcpy(ptr, a.ptr, sizeof(int) * size);
	}
}

CArray::~CArray()
{
	if (ptr)
		delete[]ptr;
}

CArray& CArray::operator=(const CArray& a) 
{
	if (ptr == a.ptr)
		return *this;
	if (a.ptr == NULL) {
		if (ptr)
			delete[]ptr;
		ptr = NULL;
		size = 0;
		return *this;
	}
	if (size < a.size) {
		if (ptr)
			delete[]ptr;
		ptr = new int[a.size];
	}
	memcpy(ptr, a.ptr, sizeof(int) * a.size);
	size = a.size;
	return *this;
}

void CArray::push_back(int v) {
	if (ptr) {
		int* tmpPtr = new int[size + 1];
		memcpy(tmpPtr, ptr, sizeof(int) * size);
		delete[]ptr;
		ptr = tmpPtr;
	}
	else {
		ptr = new int[1];
	}
	ptr[size++] = v;
}


int main() {
	CArray a;
	for (int i = 0; i < 5; i++)
		a.push_back(i);
	CArray a2, a3;
	a2 = a;
	for (int i = 0; i < a2.length(); ++i)
		cout << a2[i] << " ";
	cout << endl;
	a[3] = 100;
	CArray a4(a);
	for (int i = 0; i < a4.length(); ++i)
		cout << a4[i] << " ";
	cout << endl;
	return 0;
}